﻿namespace ContactsSync.Infrastructure.Converters
{
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Windows.Data;
    using System.Windows.Media.Imaging;

    public class ImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Image image = value as Image;
            string imageUrl = value as string;

            if (image != null)
            {
                BitmapImage bitmapImage = new BitmapImage();

                MemoryStream stream = new MemoryStream();

                image.Save(stream, ImageFormat.Bmp);
                stream.Seek(0, SeekOrigin.Begin);

                bitmapImage.BeginInit();
                bitmapImage.StreamSource = stream;
                bitmapImage.EndInit();
                return bitmapImage;
            }
            else if (!string.IsNullOrEmpty(imageUrl))
            {
                return new BitmapImage(new Uri(imageUrl, UriKind.Absolute));
            }

            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}